package com.lanou3g.k12.web.controller;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.lanou3g.k12.entity.Coupon;
import com.lanou3g.k12.entity.CouponRecord;
import com.lanou3g.k12.entity.CouponCode;
import com.lanou3g.k12.service.CouponService;
import com.lanou3g.k12.utils.K12Result;
import com.lanou3g.k12.utils.K12ResultUtils;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@RestController

public class CouponController {

    @Autowired
    private CouponService couponService;

    //查询
    @GetMapping("/coupons")
    public K12Result findAll(@RequestParam(value = "page", defaultValue = "1") Integer page,
                             String keyword,
                             @RequestParam(value = "size", defaultValue = "30") Integer size) {
        Page<Object> objects = PageHelper.startPage(page, size);
        try {
            if (keyword != null && !keyword.trim().equals("")) {
                //查关键字
                couponService.search(keyword);
            } else {
                //查询所有
                couponService.findAllCoupon();
            }
            return K12ResultUtils.ok(objects);
        } catch (Exception e) {
            e.printStackTrace();
            return K12ResultUtils.error(533);
        }
    }

    //新增兑换券

    /**
     * @param coupon 接收对象
     * @param ids    点击传来来的章节id数组
     * @return
     */
    @PostMapping("/coupon")
    public K12Result couponInsert(Coupon coupon, Long[] ids,
                                  long beginTime1,
                                  long endTime1) {
        Date date = new Date(beginTime1);
        Date date1 = new Date(endTime1);
//        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
        try {
            couponService.couponInsert(coupon, ids, date, date1);
            return K12ResultUtils.ok();
        } catch (Exception e) {
            e.printStackTrace();
            return K12ResultUtils.error(533);
        }

    }

    //通过ID查询
    @GetMapping("/coupon/{id}")
    public K12Result findCouponById(@PathVariable Long id) {
        try {
            Coupon coupon = couponService.findCouponById(id);
            return K12ResultUtils.ok(coupon);
        } catch (Exception e) {
            e.printStackTrace();
            return K12ResultUtils.error(533);
        }
    }

    //导出excel
    @GetMapping("/coupon/codes/{id}")
    public K12Result getAllCodes(@PathVariable Long id, HttpServletResponse response) {

        try {
            response.reset();
            response.setContentType("application/msexcel;charset=utf-8");
            response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode("用户信息表.xls", "UTF-8"));
            //InputStream inputStream = userService.exportByIds(ids);
            System.out.println("外层接收"+ id);
            InputStream inputStream = couponService.getAllCodes(id);
            IOUtils.copy(inputStream,response.getOutputStream());

            return K12ResultUtils.ok(200);
        } catch (Exception e) {
            e.printStackTrace();
            return K12ResultUtils.error(500);
        }
    }

    /**
     * 使用兑换码功能接口
     *
     * @param code 接收到的兑换码
     * @return 成功或者失败
     */
    @GetMapping("/voucherCode")
    public K12Result voucherCode(String code, HttpServletRequest request) {
        String phone = (String) request.getSession().getAttribute("phone");
        Boolean b = couponService.voucherCode(code, phone);
        if (b) {
            return K12ResultUtils.ok(200);
        } else {
            return K12ResultUtils.error(1400);
        }
    }

    /**
     * 查询当前用户 所有兑换卷记录
     *
     * @return 用户所有兑换卷信息
     * @request 获取域
     */
    @GetMapping("/couponRecord")
    public K12Result couponRecord(HttpServletRequest request) {
        String phone = (String) request.getSession().getAttribute("phone");
        List<CouponRecord> list = couponService.couponRecord(phone);
        return K12ResultUtils.ok(list);
    }

}
